package constant.milk.toilet.info;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import constant.milk.toilet.R;
import constant.milk.toilet.SuperActivity;
import constant.milk.toilet.bean.StickerData;
import constant.milk.toilet.bean.TimerData;
import constant.milk.toilet.broadcast.PushBroadcast;
import constant.milk.toilet.database.DbDeleteQuery;
import constant.milk.toilet.database.DbInsertQuery;
import constant.milk.toilet.database.DbSelectQuery;
import constant.milk.toilet.database.DbUpdateQuery;
import constant.milk.toilet.dialog.MilkDialog;
import constant.milk.toilet.dialog.MilkStickerDialog;
import constant.milk.toilet.util.MilkUtil;

public class InfoActivity extends SuperActivity
{
	private static final int REQUEST_CODE_INSERT = 0;
	private static final int REQUEST_CODE_UPDATE = 1;
	
	public static final String YEAR = "YEAR";
	public static final String MONTH = "MONTH";
	public static final String DAY = "DAY";
	
	private TextView preView;
	private TextView titleTextView;
	
	private TextView stickerTextView;
	private View stickerView;
	private TextView stickerSelectTextView;
	
	private TextView dateTextView;
	private TextView countTextView;
	private TextView timeTextView;
	
	private TextView titleListTextView;
	
	private TextView insertTextView;
	private TextView updateTextView;
	private TextView deleteTextView;
	
	private ListView listView;
	
	private MilkDialog dialog;
	private MilkStickerDialog stickerDialog;
	
	private DbSelectQuery select;
	
	private TimerAdapter adapter;
	
	private ArrayList<TimerData> selectList;
	
	private int year;
	private int month;
	private int day;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.info_actvity);
		
		setFindViewId();
		setOnClick();
		setData();
	}
	
	@Override
	protected void setFindViewId()
	{
		preView = (TextView) findViewById(R.id.infoPreTextView);
		titleTextView = (TextView) findViewById(R.id.infoTitleTextView);
		
		stickerTextView = (TextView) findViewById(R.id.infoStickerTextView);
		stickerView = findViewById(R.id.infoStickerView);
		stickerSelectTextView = (TextView) findViewById(R.id.infoStickerSelectTextView);
		
		dateTextView = (TextView) findViewById(R.id.infoDateTextView);
		countTextView = (TextView) findViewById(R.id.infoTodayCountTextView);
		timeTextView = (TextView) findViewById(R.id.infoTodayTimeSumTextView);
		
		titleListTextView = (TextView) findViewById(R.id.infoTitleListTextView);
		
		insertTextView = (TextView) findViewById(R.id.infoInsertView);
		updateTextView = (TextView) findViewById(R.id.infoUpdateView);
		deleteTextView = (TextView) findViewById(R.id.infoDeleteView);
		
		listView = (ListView) findViewById(R.id.listView);
	}

	@Override
	protected void setOnClick()
	{
		preView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				setResult(Activity.RESULT_OK);
				finish();
			}
		});
		
		stickerView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				stickerDialog = new MilkStickerDialog(superContext, 
						new MilkStickerDialog.StickerCollBank()
				{
					@Override
					public void getSticker(int sticker)
					{
						if (setStickerData(sticker))
						{
							if (sticker == 0)
							{
								MilkUtil.showToast(superContext, "스티커를 제거 하였습니다.");
							}
							else
							{
								MilkUtil.showToast(superContext, "스티커 변경에 성공하였습니다.");
							}
							
							setData();
						}
						else
						{
							MilkUtil.showToast(superContext, "스티커 변경에 실패하였습니다. 개발자에게 문의해주세요.");
						}
					}
				});
				
				stickerDialog.show();
			}
		});
		
		insertTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, InsertActivity.class);
				intent.putExtra(YEAR, year);
				intent.putExtra(MONTH, month);
				intent.putExtra(DAY, day);
				startActivityForResult(intent, REQUEST_CODE_INSERT);
			}
		});
		
		updateTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				selectList = new ArrayList<TimerData>();
				
				for (int i = 0; i < adapter.getCount(); i++)
				{
					TimerData data  = adapter.getItem(i);
					
					if (data.getCheckbox() > 0)
					{
						selectList.add(data);
					}
				}
				
				if (selectList.size() != 1)
				{
					dialog = new MilkDialog(superContext, 
							"수정은 하나만 선택해 주세요.", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									dialog.dismiss();
								}
							}, 
							null);
					
					dialog.setLeftTitle("확인");
					
					dialog.show();
					return;
				}
				
				Intent intent = new Intent(superContext, UpdateActivity.class);
				intent.putExtra(UpdateActivity.TIMER_ID, selectList.get(0).getId());
				startActivityForResult(intent, REQUEST_CODE_UPDATE);
			}
		});
		
		deleteTextView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				selectList = new ArrayList<TimerData>();
				
				for (int i = 0; i < adapter.getCount(); i++)
				{
					TimerData data  = adapter.getItem(i);
					
					if (data.getCheckbox() > 0)
					{
						selectList.add(data);
					}
				}
				
				if (selectList.size() < 1)
				{
					dialog = new MilkDialog(superContext, 
							"선택 된 목록이 하나도 없습니다.", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									dialog.dismiss();
								}
							}, 
							null);
					
					dialog.setLeftTitle("확인");
				}
				else
				{
					dialog = new MilkDialog(superContext, 
							"선택 된 목록을 삭제 하시겠습니까?", 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									if (setDeleteData(selectList))
									{
										MilkUtil.showToast(superContext, "삭제에 성공 하였습니다.");
										
										setData();
									}
									else
									{
										MilkUtil.showToast(superContext, "삭제에 실패 하였습니다.");
									}
									
									dialog.dismiss();
								}
							}, 
							new OnClickListener()
							{
								@Override
								public void onClick(View v)
								{
									dialog.dismiss();
								}
							});
				}
				
				if (dialog != null)
				{
					dialog.show();
				}
			}
		});
	}

	@Override
	protected void setData()
	{
		select = new DbSelectQuery(superContext, superDb);
		
		titleTextView.setTextColor(Color.WHITE);
		titleListTextView.setTextColor(Color.WHITE);
		
		titleTextView.setTextSize(TEXT_SIZE + 2);
		titleListTextView.setTextSize(TEXT_SIZE + 2);
		stickerTextView.setTextSize(TEXT_SIZE + 2);
		
		Calendar cal = Calendar.getInstance();
		
		Intent intent = getIntent();
		year = intent.getIntExtra(YEAR, cal.get(Calendar.YEAR));
		month = intent.getIntExtra(MONTH, cal.get(Calendar.MONTH));
		day = intent.getIntExtra(DAY, cal.get(Calendar.DAY_OF_MONTH));
		
		StickerData stickerData = select.getStickerDate(year, month, day);
		if (stickerData == null)
		{
			stickerSelectTextView.setBackgroundResource(0);
		}
		else
		{
			stickerSelectTextView.setBackgroundResource(MilkUtil.getSticker(stickerData.getSticker()));
		}
		
		ArrayList<TimerData> list = select.getTimerList(year, month, day);
		
		dateTextView.setText(MilkUtil.getDateCom(year, month+1, day));
		countTextView.setText("총 " + list.size() + "번");
		
		long sumTime = 0;
		
		for (int i = 0; i < list.size(); i++)
		{
			TimerData data  = list.get(i);
			sumTime = sumTime + Long.parseLong(data.getTerm());
		}
		
		timeTextView.setText(getTermTime(sumTime));
		
		adapter = new TimerAdapter(superContext, R.layout.list_item_timer, list);
		listView.setOnItemClickListener(onItemClickListener);
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}
	
	@Override
	public void onBackPressed()
	{
		setResult(Activity.RESULT_OK);
		super.onBackPressed();
	}
	
	private boolean setDeleteData(ArrayList<TimerData> list)
	{
		DbDeleteQuery query = null;
		
		try
		{
			query = new DbDeleteQuery(superContext, superDb);
			
			query.setBeginTansaction();
			
			for (int i = 0; i < list.size(); i++)
			{
				query.deleteTimer(list.get(i).getId());
			}
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setStickerData(int sticker)
	{
		DbInsertQuery insertQuery = null;
		DbUpdateQuery updateQuery = null;
		
		try
		{
			insertQuery = new DbInsertQuery(superContext, superDb);
			updateQuery = new DbUpdateQuery(superContext, superDb);
			
			insertQuery.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("year", year + "");
			map.put("month", month + "");
			map.put("day", day + "");
			map.put("sticker", sticker + "");
			
			StickerData data = select.getStickerDate(year, month, day);
			
			if (data == null)
			{
				insertQuery.insertSticker(map);
			}
			else
			{
				updateQuery.updateSticker(map, data.getId());
			}
			
			Calendar cal = Calendar.getInstance();
			int toYear = cal.get(Calendar.YEAR);
			int toMonth = cal.get(Calendar.MONTH);
			int toDay = cal.get(Calendar.DAY_OF_MONTH);
			
			if (toYear == year && toMonth == month && toDay == day)
			{
				SharedPreferences p = getSharedPreferences("pref", Activity.MODE_PRIVATE);
				
				int alarmPush = p.getInt(getString(R.string.prefPushAlarm), 1);
				
				if (alarmPush > 1)
				{
					Intent intent = new Intent(superContext, PushBroadcast.class);    
					PendingIntent sender = PendingIntent.getBroadcast(superContext, 1, intent, 
							PendingIntent.FLAG_CANCEL_CURRENT);
					
			        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
			        manager.cancel(sender);
			        
			        int version = Build.VERSION.SDK_INT;
					
					if (version >= 19)
					{
						manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (24 * 60 * 60000), sender);
					}
					else
					{
						manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (24 * 60 * 60000), sender);
					}
			        
			        SharedPreferences.Editor e = p.edit();
			        
			        e.putInt(getString(R.string.prefPushAlarm), 1);
			        e.commit();
				}
			}
			
			insertQuery.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				insertQuery.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private String getTermTime(long termDate)
	{
		Calendar calT = Calendar.getInstance();
		calT.setTimeInMillis(termDate);
		
		String termStr = "";
		
		int year = calT.get(Calendar.YEAR);
		int month = calT.get(Calendar.MONTH);
		int day = calT.get(Calendar.DAY_OF_MONTH);
		int hour = calT.get(Calendar.HOUR_OF_DAY);
		int minute = calT.get(Calendar.MINUTE);
		int second = calT.get(Calendar.SECOND);
		
		year = year - 1970;
		month = month -1;
		day = day - 1;
		hour = hour - 9;
		
		if (year > 0)
		{
			termStr = termStr + year + "년 ";
		}
		
		if (month > -1)
		{
			termStr = termStr + (month+1) + "월 ";
		}
		
		if (day > 0)
		{
			termStr = termStr + day + "일 ";
		}
		
		if (hour > 0)
		{
			termStr = termStr + hour + "시간 ";
		}
		
		if (minute > 0)
		{
			termStr = termStr + minute + "분 ";
		}
		
		if (second > 0)
		{
			termStr = termStr + second + "초";
		}
		
		if (termStr.equals(""))
		{
			termStr = "0초";
		}
		
		return termStr;
	}
	
	private OnItemClickListener onItemClickListener = new OnItemClickListener()
	{
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3)
		{
			TimerData data = (TimerData) arg0.getItemAtPosition(position);
			
			if (data.getCheckbox() == 0)
			{
				data.setCheckbox(1);
			}
			else
			{
				data.setCheckbox(0);
			}
			
			adapter.notifyDataSetChanged();
		}
	};
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		if (resultCode != Activity.RESULT_OK)
		{
			return;
		}
		
		if (requestCode == REQUEST_CODE_INSERT)
		{
			setData();
		}
		else if (requestCode == REQUEST_CODE_UPDATE)
		{
			setData();
		}
	};
	
	public class TimerAdapter extends ArrayAdapter<TimerData>
	{

		public TimerAdapter(Context context, int resource,
				List<TimerData> objects)
		{
			super(context, resource, objects);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			View v = convertView;
			
			if (v == null) 
			{
				LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflater.inflate(R.layout.list_item_timer, null);
			}
			
			TimerData data = getItem(position);
			
			TextView startTextView = (TextView) v.findViewById(R.id.listItemTimerStartTextView);
			TextView endTextView = (TextView) v.findViewById(R.id.listItemTimerEndTextView);
			TextView termTextView = (TextView) v.findViewById(R.id.listItemTimerTermTextView);
			TextView checkbox = (TextView) v.findViewById(R.id.listItemTimerCheckBox);
			
			startTextView.setTextSize(TEXT_SIZE);
			endTextView.setTextSize(TEXT_SIZE);
			termTextView.setTextSize(TEXT_SIZE);
			
			long startDate = Long.parseLong(data.getStarttime());
			long termDate = Long.parseLong(data.getTerm());
			long endDate = startDate + termDate;
			
			Calendar calS = Calendar.getInstance();
			calS.setTimeInMillis(startDate);
			
			Calendar calE = Calendar.getInstance();
			calE.setTimeInMillis(endDate);
			
			startTextView.setText(MilkUtil.getTimeStr(
					calS.get(Calendar.HOUR_OF_DAY), calS.get(Calendar.MINUTE)));
			endTextView.setText(MilkUtil.getTimeStr(
					calE.get(Calendar.HOUR_OF_DAY), calE.get(Calendar.MINUTE)));
			
			String termStr = getTermTime(termDate);
			
			termTextView.setText("(" + termStr + ")");
			
			if (data.getCheckbox() == 1)
			{
				checkbox.setBackgroundResource(R.drawable.ic_font_checkbox);
			}
			else
			{
				checkbox.setBackgroundResource(0);
			}
			
			return v;
		}
	}
}
